package com.example.demo.config;


import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.example.demo.shiro.CustomRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.mgt.SessionsSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
     @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
    //将自己的验证方式加入容器
    @Bean
    public CustomRealm myShiroRealm() {
        CustomRealm customRealm = new CustomRealm();
        return customRealm;
    }

    //权限管理，配置主要是Realm的管理认证
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());
        return securityManager;
    }
    //Filter工厂，设置对应的过滤条件和跳转条件
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map<String, String> map = new LinkedHashMap<>();
        //过滤器种类
//        1.anon 无需认证
//        2.authc 必须认证
//        3.user 记住我可以访问
//        4.perms 授予权限才可以访问
//        5.role 授予角色才可以访问

        //登录
        shiroFilterFactoryBean.setLoginUrl("/denglu");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        //登出
        map.put("/user/logout", "logout");
        map.put("/user/denglu","anon");
        //对所有用户认证
//        map.put("/*/**", "authc");

        return shiroFilterFactoryBean;
    }

}
